<!-- 添加轮播图 -->
<template>
    <el-form ref="bannerRef" :rules="rules" :model="formatData" style="max-width: 460px">
        <el-form-item label="图片">
            <el-upload ref="upload" :limit="1" :on-exceed="handleExceed" :on-change="onChange" :auto-upload="false"
                list-type="picture" porp="img">
                <template #trigger>
                    <el-button type="primary">上传文件</el-button>
                </template>
            </el-upload>
        </el-form-item>
        <el-form-item label="地址" porp="link">
            <el-input v-model="formatData.link" />
        </el-form-item>
        <el-form-item label="文案" porp="alt">
            <el-input v-model="formatData.alt" />
        </el-form-item>
        <el-form-item>
            <el-button type="success" @click="submitForm(bannerRef)">
                提交
            </el-button>
            <el-button @click="resetForm(bannerRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { genFileId } from 'element-plus';
import { addBanner } from '../../../../services/index';
const formatData = reactive(
    {
        img: '',
        alt: '',
        link: ''
    }
)
const rules = reactive(
    {
        img: [
            { required: true, trigger: 'blur', message: '请选择图片' }
        ],
        alt: [
            { required: true, trigger: 'blur', message: '请填写序号' }
        ],
        link: [
            { required: true, trigger: 'blur', message: '请填写地址' }
        ]
    }
)
// 规定只能传入一个图片文件，后传入的将覆盖先传入的
let upload = ref();
const handleExceed = files => {
    //获取上传组件
    console.log(upload);
    upload.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    upload.value.handleStart(file)
}
const onChange = (files) => {
    console.log(formatData);
    //创建一个异步读取文件
    const fileReader = new FileReader();
    //将文件读取为字符串形式
    fileReader.readAsDataURL(files.raw)
    // 异步将上传的图片更改为读取的字符串形式
    fileReader.onload = () => {
        formatData.img = fileReader.result
    }
}
const emit = defineEmits(['add-succuss'])
let bannerRef = ref();
console.log(bannerRef, 1);
const submitForm = async () => {
    await bannerRef.value.validate((valid) => {
        if (valid) {
            addBanner(formatData).then((result) => {
                emit('add-succuss')
                // 清空
                // bannerRef.value.resetFields()
                formatData.alt = '';
                formatData.link = '';
                console.log(bannerRef.value);
                upload.value.clearFiles()
            })
        }
    })
}

</script>